﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Domain.Material;
using ProduceBasicData.Domain.FactoryModeling;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;
using System.Linq;
using ProduceBasicData.Api.Application.Command.Material.BOM;

namespace ProduceBasicData.Api.Application.Handler.Material.BOM
{
    /// <summary>
    /// 新增BOM处理
    /// </summary>
    public class CreateBOMHandler : IRequestHandler<CreateBOMCommand, ApiResult<int>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRespository<BOMInfoModel> bomRepository;
        private readonly IBaseRespository<ProductMaterialModel> productMaterialRepository;
        private readonly IBaseRespository<ProcessModel> processRepository;

        public CreateBOMHandler(IMapper mapper, IBaseRespository<BOMInfoModel> bomRepository, IBaseRespository<ProductMaterialModel> productMaterialRepository, IBaseRespository<ProcessModel> processRepository)
        {
            this.mapper = mapper;
            this.bomRepository = bomRepository;
            this.productMaterialRepository = productMaterialRepository;
            this.processRepository = processRepository;
        }

        public async Task<ApiResult<int>> Handle(CreateBOMCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            //// 防重复：同名同版本视为重复
            //var isDuplicate = bomRepository
            //    .GetAll()
            //    .Any(x => !x.Isdel
            //        && x.BOMName == request.BOMName
            //        && x.BomVersion == request.BomVersion);

            //if (isDuplicate)
            //{
            //    result.Code = ApiEnum.Failed;
            //    result.Msg = "已存在相同名称与版本的BOM";
            //    result.Data = 0;
            //    return await Task.FromResult(result);
            //}

            // 验证ProcessId是否存在
            if (request.ProcessId > 0)
            {
                var process = await processRepository.GetModelAsync(request.ProcessId);
                if (process == null || process.Isdel)
                {
                    result.Code = ApiEnum.Failed;
                    result.Msg = "指定的工序不存在，请检查ProcessId";
                    result.Data = 0;
                    return await Task.FromResult(result);
                }
            }
            else
            {
                result.Code = ApiEnum.Failed;
                result.Msg = "ProcessId不能为空或0";
                result.Data = 0;
                return await Task.FromResult(result);
            }

            var entity = mapper.Map<BOMInfoModel>(request);
            // 元数据填充
            entity.CreateTime = DateTime.Now;
            entity.CreateName = request.CreateName;
            entity.UpdateTime = request.UpdateTime ?? DateTime.Now;
            entity.UpdateName = request.UpdateName;

            // 确保BOMDosage有默认值
            if (!entity.BOMDosage.HasValue)
            {
                entity.BOMDosage = 1; // 默认用量为1
            }

            // 处理上下级关系
            if (request.IsChild)
            {
                BOMInfoModel parent = null;

                // 优先使用ParentBOMId，如果没有则通过名称和版本查找
                if (request.ParentBOMId.HasValue && request.ParentBOMId.Value > 0)
                {
                    parent = await bomRepository.GetModelAsync(request.ParentBOMId.Value);
                }
                else if (!string.IsNullOrWhiteSpace(request.ParentBOMName) && !string.IsNullOrWhiteSpace(request.ParentBomVersion))
                {
                    parent = bomRepository.GetAll()
                        .FirstOrDefault(x => !x.Isdel && x.BOMName == request.ParentBOMName && x.BomVersion == request.ParentBomVersion);
                }

                if (parent != null && !parent.Isdel)
                {
                    // 设置父子关系
                    entity.ParentBOMId = parent.Id;
                    entity.BOMLevel = parent.BOMLevel + 1;

                    // 设置BOM阶别，用于显示层级
                    entity.BOMSteps = $"{parent.BOMSteps}.{parent.BOMLevel + 1}";

                    // 如果父级有工序信息，子级可以继承或使用自己的工序
                    if (request.ProcessId == 0 && parent.ProcessId > 0)
                    {
                        entity.ProcessId = parent.ProcessId;
                    }
                }
                else
                {
                    // 如果找不到父级BOM，返回错误
                    result.Code = ApiEnum.Failed;
                    result.Msg = "未找到指定的父级BOM，无法添加下级";
                    result.Data = 0;
                    return await Task.FromResult(result);
                }
            }
            else
            {
                // 顶级BOM，设置初始层级
                entity.ParentBOMId = null;
                entity.BOMLevel = 0;
                entity.BOMSteps = "1";
            }

            // 生成BOM编码（如果未提供）
            if (string.IsNullOrWhiteSpace(entity.BOMCode))
            {
                entity.BOMCode = await GenerateBOMCode(entity.BOMLevel, entity.ParentBOMId);
            }

            // 设置群组物料ID
            if (request.MaterialGroupId.HasValue && request.MaterialGroupId.Value > 0)
            {
                entity.MaterialGroupId = request.MaterialGroupId.Value;
            }

            // 若提供了产品物料Id，则从产品物料填充BOM相关字段
            if (request.ProductMaterialId.HasValue && request.ProductMaterialId.Value > 0)
            {
                var pm = await productMaterialRepository.GetModelAsync(request.ProductMaterialId.Value);
                if (pm != null && !pm.Isdel)
                {
                    // 将与BOM对应的字段从产品物料带入（按现有模型可映射的项）
                    entity.BOMDesc = string.IsNullOrWhiteSpace(entity.BOMDesc) ? pm.ProductDesc : entity.BOMDesc;
                    // 其他如名称/类型若未填则采用产品物料信息
                    entity.BOMName = string.IsNullOrWhiteSpace(entity.BOMName) ? pm.ProductName : entity.BOMName;
                    entity.BomType = string.IsNullOrWhiteSpace(entity.BomType) ? pm.GroupType : entity.BomType;
                    // 设置产品物料ID
                    entity.ProductMaterialId = request.ProductMaterialId.Value;
                }
            }

            var rows = await bomRepository.AddAsync(entity);
            result.Code = ApiEnum.Success;
            result.Msg = "新增BOM成功";
            result.Data = rows;
            return await Task.FromResult(result);
        }

        /// <summary>
        /// 生成BOM编码
        /// </summary>
        /// <param name="level">BOM层级</param>
        /// <param name="parentId">父级BOM ID</param>
        /// <returns>生成的BOM编码</returns>
        private async Task<string> GenerateBOMCode(int level, int? parentId)
        {
            var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");

            if (parentId.HasValue && parentId.Value > 0)
            {
                // 子级BOM，基于父级编码生成
                var parent = await bomRepository.GetModelAsync(parentId.Value);
                if (parent != null)
                {
                    // 获取同级子BOM数量，用于生成序号
                    var siblingCount = bomRepository.GetAll()
                        .Count(x => !x.Isdel && x.ParentBOMId == parentId.Value);

                    return $"{parent.BOMCode}-{siblingCount + 1:D2}";
                }
            }

            // 顶级BOM，生成新的编码
            var topLevelCount = bomRepository.GetAll()
                .Count(x => !x.Isdel && x.ParentBOMId == null);

            return $"BOM{topLevelCount + 1:D3}-{timestamp.Substring(8)}";
        }
    }
}
